package com.neteast.androidclient.newscenter.adapter;

import java.io.File;
import java.lang.ref.SoftReference;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import com.neteast.androidclient.newscenter.Global;
import com.neteast.androidclient.newscenter.R;
import com.neteast.androidclient.newscenter.domain.Information;
import com.neteast.androidclient.newscenter.util.ConfigUtil;
import com.neteast.androidclient.newscenter.util.DateUtil;
import com.neteast.androidclient.newscenter.util.ImageUtil;
import com.neteast.androidclient.newscenter.util.LoginUtil;
import com.neteast.androidclient.newscenter.util.StringUtil;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 
 * @author tiangh
 *
 */
public class InfoListAdapter extends BaseAdapter {

	private LayoutInflater inflater;
	private ArrayList<Information> informations;
	private Resources resources;
	private Context context;
	private int userId;
	private static HashMap<Long, SoftReference<Bitmap>> imageCache;
	
	
	public InfoListAdapter(Context context, ArrayList<Information> informations) {
		this.context=context;
		inflater=LayoutInflater.from(context);
		this.informations=informations;
		resources = context.getResources();
		userId = LoginUtil.getUserId(context);
		imageCache=new HashMap<Long, SoftReference<Bitmap>>();
	}
	
	@Override
	public int getCount() {
		return informations.size();
	}

	@Override
	public Object getItem(int position) {
		return informations.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Information info = informations.get(position);
		ViewHolder holder;
		if (convertView==null) {
			holder=new ViewHolder();
			convertView=inflater.inflate(R.layout.main_info_list_item, null);
			holder.title=(TextView) convertView.findViewById(R.id.title);
			holder.image=(ImageView) convertView.findViewById(R.id.image);
			holder.content=(TextView) convertView.findViewById(R.id.content);
			holder.time=(TextView) convertView.findViewById(R.id.time);
			holder.delete=(CheckBox) convertView.findViewById(R.id.delete);
			holder.showAll=(Button) convertView.findViewById(R.id.show_all);
			convertView.setTag(holder);
		}else {
			holder=(ViewHolder) convertView.getTag();
		}
		//设置标题
		setTitle(info,holder.title);
		//设置图片
		setImage(info,holder.image);
		//设置内容
		setContent(info,holder.content,holder.showAll);
		//设置发送时间
		setSendTime(info.sendTime,holder.time);
		//设置删除按钮
		setDeleteBtn(info,holder.delete);
		return convertView;
	}
	
	

	private void setTitle(Information info, TextView title) {
		switch (info.infoTypeId) {
		default:
		case Global.INFO_TYPE_SYS:
			title.setText(R.string.info_system_title);
			break;
		case Global.INFO_TYPE_APP:
			title.setText(info.appName);
			break;
		case Global.INFO_TYPE_INTERACTIVE:
			title.setText(Html.fromHtml("来自：<font color=#ff7200>"+info.userName+"</font>"));
			break;
		}
	}
	private void setDeleteBtn(final Information info, final CheckBox delete) {
		switch (info.infoTypeId) {
		default:
		case Global.INFO_TYPE_SYS:
			delete.setVisibility(View.INVISIBLE);
			break;
		case Global.INFO_TYPE_APP:
		case Global.INFO_TYPE_INTERACTIVE:
			delete.setVisibility(View.VISIBLE);
			break;
		}
		delete.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				//设置了删除确认提示的，必须按钮被选择后再点击然后才删除
				if (ConfigUtil.getDeleteConfirm(context, userId)) {
					if (isChecked) {}
					else {
						deleteInfo(info);
						notifyDataSetChanged();
					}
				}
				//没有设置删除确认提示的，直接删除，并且删除后，不把选择状态设置为已经选择
				else {
					buttonView.setChecked(false);
					deleteInfo(info);
					notifyDataSetChanged();
				}
			}
		});
	}
	private void deleteInfo(Information info){
		ImageUtil.deleteInfo(info, context);
		imageCache.remove(info.infoId);
		informations.remove(info);
	}
	private void setImage(Information info, ImageView image) {
		image.setVisibility(View.GONE);
		//从内存里读取
		if (imageCache.containsKey(info.infoId)) {
			Bitmap bitmap =  imageCache.get(info.infoId).get();
			if (bitmap!=null) {
				image.setImageBitmap(bitmap);
				image.setVisibility(View.VISIBLE);
				return;
			}
		}
		//内存里没有， 从文件里读取，并放入内存缓存
		File saveFile = ImageUtil.makeSaveFile(info, context);
		if (saveFile!=null&&saveFile.exists()&&saveFile.isFile()) {
			Bitmap bitmap = ImageUtil.getImageFile(info, context);
			if (bitmap!=null) {
				imageCache.put(info.infoId, new SoftReference<Bitmap>(bitmap));
				image.setImageBitmap(bitmap);
				image.setVisibility(View.VISIBLE);
				image.invalidate();
				return;
			}
		}
		//内存文件都没有，则从网络下载，并放入内存缓存
		if (info.picUrl!=null&&!info.picUrl.equals("")) {
			showImage(info, image);
			image.setVisibility(View.VISIBLE);
		}
	}

	private void setContent(final Information info, final TextView contentTV, final Button showAll) {
		try {
			Object[] objects = StringUtil.formatInfoContent(info.textContent);
			final int start=(Integer) objects[0];
			final int end=(Integer) objects[1];
			final String content=(String) objects[2];
			final String url=info.goURL;
			SpannableString ss=new SpannableString(content);
			XmlResourceParser contentLinkParser = resources.getXml(R.color.info_content_link);
			ColorStateList content_color_link=ColorStateList.createFromXml(resources, contentLinkParser);
			
			if (!TextUtils.isEmpty(url)) {
				final boolean b=new URI(url).isAbsolute();
				if (info.infoTypeId==Global.INFO_TYPE_SYS&&b) {
					ss.setSpan(new URLSpan(url), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
				//对消息内容里链接部分着色
				ss.setSpan(new TextAppearanceSpan(null, Typeface.NORMAL, 16, content_color_link,null),start,end,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				ss.setSpan(new ClickableSpan() {
					@Override
					public void onClick(View widget) {
						if (!b){
							Toast.makeText(context, "Url地址不合法", Toast.LENGTH_SHORT).show();
						}
						if (info.infoTypeId==Global.INFO_TYPE_APP&&b) {
							if (content.indexOf("转码成功.")!=-1) {
								Intent intent= new Intent();        
				                intent.setAction(Intent.ACTION_VIEW);    
				                intent.putExtra("url", url);
				                intent.putExtra("fileName", content.trim().replaceAll("转码成功.", ""));
				                intent.setClassName("com.neteast.video","com.neteast.video.activity.MainActivity");  
				                context.startActivity(intent);
							}
						}
					}
					@Override
					public void updateDrawState(TextPaint ds) {
						ds.setUnderlineText(false);
					}
				}, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			contentTV.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
				@Override
				public boolean onPreDraw() {
					final int lineCount = contentTV.getLineCount();
					showAll.setVisibility(View.GONE);
					if (lineCount>0) {
						contentTV.getViewTreeObserver().removeOnPreDrawListener(this);
					}
					if (lineCount>6) {
						contentTV.setMaxLines(6);
						showAll.setVisibility(View.VISIBLE);
						showAll.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								showAll.setVisibility(View.GONE);
								contentTV.setMaxLines(lineCount);
							}
						});
					}
					return true;
				}
			});
			contentTV.setText(ss);
			contentTV.setMovementMethod(LinkMovementMethod.getInstance());
			
		} catch (Exception e) {
			Log.e("test", e.getMessage());
		}
	}

	private void setSendTime(Long sendTime, TextView time) {
		time.setText(DateUtil.formatDate(sendTime));
	}
	
	static class ViewHolder{
		TextView title;
		ImageView image;
		TextView content;
		TextView time;
		CheckBox delete;
		Button showAll;
	}
	
	private void showImage(Information information,final ImageView imageView){
		LoadImageTask imageTask=new LoadImageTask();
		//参数传给了doInBackground()
		imageTask.execute(information,imageView);
	}
	
	public class LoadImageTask extends AsyncTask<Object, Integer, Bitmap> {

		private Information information;
		private ImageView imageView;

		@Override
		protected Bitmap doInBackground(Object... params) {
			information=(Information) params[0];
			imageView = (ImageView) params[1];
			File saveFile = ImageUtil.makeSaveFile(information,context);
			try {
				ImageUtil.downLoadImage(information.picUrl,saveFile);
				Bitmap bitmap = ImageUtil.getImageFile(information, context);
				imageCache.put(information.infoId, new SoftReference<Bitmap>(bitmap));
				return bitmap;
			} catch (Exception e) {
				return null;
			}
		}
		@Override
		protected void onPostExecute(Bitmap result) {
			imageView.setImageBitmap(result);
		}
	}
}
